package com.smit.livevideo.sample.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.smit.dvb.DVBServiceInfo;
import com.smit.dvb.service.IServiceCallback;
import com.smit.dvb.service.ServiceControl;
import com.smit.livevideo.R;
import com.smit.livevideo.sample.controller.CIMMIController;
import com.smit.livevideo.sample.controller.ScanServicesController;
import com.smit.livevideo.sample.dao.ChannelDAO;
import com.smit.livevideo.sample.fragment.BaseFragment;
import com.smit.livevideo.sample.fragment.FragmentUtil;
import com.smit.livevideo.sample.player.PlayerThread;
import com.smit.livevideo.sample.util.LivevideoUtil;
import com.smit.livevideo.sample.util.SDKAPIUtil;
import com.smit.utils.LogUtil;

/**
 * Created by smfang on 2015/12/7.
 * 融合电视进入直播需要调用LivevideoActivity
 */
public class LiveVideoActivity extends BaseActivity implements IServiceCallback, Handler.Callback {
    private static final String TAG = LiveVideoActivity.class.getSimpleName();
    private PlayerThread playerThread = null;
    private SurfaceView surfaceView;

    private Handler msgHandler;
    private CIMMIController cimmiController;
    /******************************************
     * 视图
     ******************************************/
    private View vSmallTipContainer;
    private FrameLayout fullBack;

    private TextView tvSmallTipText; // 屏幕中央的提示条信息
    private ImageView ivTestingWatermark;

    private Intent channelIntent = null; // 外部启动我们activity的intent
    private boolean firstTimePlay = true;

    private Runnable showEncryptMsg = new Runnable() {
        @Override
        public void run() {
            showSmallTip(R.string.tips_encrypt_program);
        }
    };

    private void initItems() {
        vSmallTipContainer = findViewById(R.id.fl_livevideo_small_tip_container);
        tvSmallTipText = (TextView) findViewById(R.id.tv_livevideo_small_tip_text);
        ivTestingWatermark = (ImageView) findViewById(R.id.iv_testing_watermark);
        surfaceView = (SurfaceView) this.findViewById(R.id.sf_livevideo_surface_view);
        fullBack = (FrameLayout) this.findViewById(R.id.fl_full_back);
    }

    private void initPlayer() {
        LogUtil.debug(TAG, "initPlayer~~~");

        if (playerThread == null) {
            playerThread = new PlayerThread();
            playerThread.setSurfaceHolder(surfaceView);

//            playerThread.setSurfaceHolder(surfaceView, new MediaPlayerController.HideFullBack()
//            {
//                @Override
//                public void hideFullBackCallback()
//                {
//                    vSmallTipContainer.setVisibility(View.GONE);
//                    if (fullBack.getVisibility() == View.VISIBLE)
//                    {
//                        fullBack.setVisibility(View.GONE);
//                        fullBack.invalidate();
//                    }
//                }
//            });

            if (!playerThread.isAlive()) {
                playerThread.setName("playerThread");
                playerThread.start();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.debug(TAG, "onCreate~~~~~");
        /* 要放在oncreate之前，因为baseactivity的oncreate会启动service */
        cimmiController = CIMMIController.getInstance();
        SDKAPIUtil.getServiceControl().addCallback(this);
        cimmiController.initCIMMIController(this);
        setContentView(R.layout.activity_livevideo);
        msgHandler = new Handler(this);
        initItems();
        initPlayer();
        playerThread.setbPlayerError(false);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        /* 其他应用启动这个应用，并传递播放节目的信息过来 */
        LogUtil.debug(TAG, "onNewIntent~~~~~");
        channelIntent = intent;
        firstTimePlay = true;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.debug(TAG, "onRestart~~~~~");
        firstTimePlay = true;
        /*
         * 如果在直播的过程中进入待机，再次起来会出现播放失败， 不同的平台出现情况不一样 为了统一处理， 这里解决的办法就是退出应用，让用户重新进入
         */
        initPlayer();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        LogUtil.debug(TAG, "onResume~~~~~");
        /*
         * 要放在super.onResume之前，因为super.onResume会去调用DVBService，
         * 然后会回调到onCamUsbInitOk();如果这个时候还没有dvb resume，是无法播放的。 拔插dongle会导致播放无法启动。
         */
        playerThread.setPlayerHasReset(false);
        SDKAPIUtil.getSystemControl().resume();
        super.onResume();
        /* 其他应用启动这个应用，并传递播放节目的信息过来 */
        if (channelIntent == null) {
            channelIntent = getIntent();
        }

        deviceInitOK();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.debug(TAG, "onKeyDown:" + event.toString());
        /* 还没有进行第一次播放处理前，不要响应按键 */
//        if (firstTimePlay || DVB_DEVICE.getStatus() == DVBDevice.DVB_DEVICE_DISCONNECTED) {
//            if (DVB_DEVICE.getStatus() == DVBDevice.DVB_DEVICE_DISCONNECTED && keyCode == KeyEvent.KEYCODE_BACK) {
//                exitLiveApp(true);
//            }
//            return true;
//        }

        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_CHANNEL_UP:
            case KeyEvent.KEYCODE_MEDIA_REWIND:
            case 328:// KeyEvent.KEYCODE_MTKIR_CHUP
                LivevideoUtil.playServicesRewind();
                resetPlayer();
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_CHANNEL_DOWN:
            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
            case 331:// KeyEvent.KEYCODE_MTKIR_CHDN
                LivevideoUtil.playServicesForward();
                resetPlayer();
                break;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                SDKAPIUtil.getCIControl().openSession();
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                CIMMIController.getSomeInfo();
                break;
            case KeyEvent.KEYCODE_BACK:
                exitApk(false);
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 消息处理
     *
     * @param msg 消息值
     * @return boolean
     */
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case ServiceControl.MSG_SERVICE_HAS_TS:
                serviceHasTS();
                break;
            case ServiceControl.MSG_SERVICE_FREE_AND_RESET_PLAYER:
                serviceFreeAndResetPlayer();
                break;
            case ServiceControl.MSG_SERVICE_FREE_WITHOUT_RESET_PLAYER:
                serviceFreeWithoutResetPlayer();
                break;
            case ServiceControl.MSG_SERVICE_SCRAMBLED:
                serviceScrambled();
                break;
            case ServiceControl.MSG_SERVICE_TS_PLAYER_PREPARED:
                serviceTsPlayerPrepared();
                break;
            case ServiceControl.MSG_SERVICE_SIGNAL_BAD:
                serviceSignalBad();
                break;
            case ServiceControl.MSG_SERVICE_SIGNAL_GOOD:
                serviceSignalGood();
                break;
            case ServiceControl.MSG_SERVICE_STOPPED:
                serviceStop();
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    protected void onPause() {
        LogUtil.trace(TAG, "onPause~~~~~:" + ScanServicesController.isDVBScaning());
        if (ScanServicesController.isDVBScaning()) {
            FragmentUtil.popAllBackStack(getFragmentManager());
            SDKAPIUtil.getScanControl().abortScan();
        }
        if (isFinishing()) {
            LogUtil.debug(TAG, "onPause~~~~~isFinishing~ServiceStop");
            SDKAPIUtil.getServiceControl().stopDVBService();
        }
        super.onPause();
    }

    @Override
    protected void onStop() {
        LogUtil.debug(TAG, "onStop~~~~~");
        firstTimePlay = true;

        if (channelIntent != null) {
            channelIntent = null;
        }
        setIntent(null); //清空intent，避免重新进入获取到上次的intent
        releasePlayerData();
        SDKAPIUtil.getScanControl().abortScan();
        SDKAPIUtil.getServiceControl().stopDVBService();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        LogUtil.debug(TAG, "onDestroy~~~~~");
        SDKAPIUtil.getServiceControl().removeCallback(this);
        cimmiController.freeCIMMIController();
        cimmiController = null;
        surfaceView = null;
        showEncryptMsg = null;
        FragmentUtil.releaseFragments();
        super.onDestroy();
        /* 加快系统GC */
    }

    @Override
    public boolean isMediaPlayerError() {
        boolean mediaPlayerError = false;

        if (playerThread != null) {
            mediaPlayerError = playerThread.isbPlayerError();
        }

        return mediaPlayerError;
    }

    /**
     * 释放player所有相关数据，onstop时候调用
     */
    public void releasePlayerData() {
        LogUtil.debug(TAG, "releasePlayerData~~~");
        if (playerThread != null) {
            playerThread.interrupt();
            playerThread.freePlayer();
        }
        playerThread = null;
    }

    /**
     * 复位player
     */
    public void resetPlayer() {
        if (playerThread != null) {
            playerThread.resetPlayer();
        }
        vSmallTipContainer.setVisibility(View.GONE);
    }

    /**
     * 显示直播节目的小提示UI
     *
     * @param strId string的id值
     */
    public void showSmallTip(int strId) {
        vSmallTipContainer.setVisibility(View.GONE);
        tvSmallTipText.setText(strId);
        fullBack.setVisibility(View.VISIBLE);
        vSmallTipContainer.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏直播界面的小提示
     */
    public void hideSmallTip() {
        vSmallTipContainer.setVisibility(View.GONE);
    }

    /**
     * 监听到按下home键后调用
     */
    void onHomePressed() {
        LogUtil.debug(TAG, "onHomePressed~~~");
        super.onHomePressed();
    }

    /**
     * 设备连接回调处理
     */
    public void deviceConnected() {
        LogUtil.debug(TAG, "deviceConnected~~~~");
        super.deviceConnected();
    }

    /**
     * 设备初始化OK回调处理
     */
    public void deviceInitOK() {
        LogUtil.trace(TAG, "deviceInitOK~~~~");
        super.deviceInitOK();

        if (ChannelDAO.getInstance().queryAllChannelList().size() == 0) {
            LogUtil.trace(TAG, "mDvbAdapter.getChannelNum() == 0");
            BaseFragment lastFragment = FragmentUtil.getLastFragment();
            LogUtil.trace(TAG, "lastFragment = " + lastFragment);
            showSmallTip(R.string.no_program_info);
        } else {
            LogUtil.trace(TAG, "deviceConnected~~~playLastServices");
            firstTimePlay = false;
            SDKAPIUtil.getSetupControl().setServiceGroupId(DVBServiceInfo.DVB_GROUP_TV);
            LivevideoUtil.playLastServices();
        }
    }

    /**
     * 设备断开回调处理
     */
    public void deviceDisconnect() {
        LogUtil.trace(TAG, "deviceDisconnect~~~");
        FragmentUtil.popAllBackStack(getFragmentManager());
        if (ScanServicesController.isDVBScaning()) {
            SDKAPIUtil.getScanControl().abortScan();
        }
        SDKAPIUtil.getServiceControl().stopDVBService();
        if (playerThread != null) {
            playerThread.resetPlayer();
        }

        super.deviceDisconnect();
    }

    /**
     * DVB播放消息回调：有TS流
     */
    public void serviceHasTS() {
        LogUtil.debug(TAG, "serviceHasTS~~~~");
        msgHandler.removeCallbacks(showEncryptMsg);
        hideSmallTip();
    }

    /**
     * DVB播放消息回调：释放并且复位player
     */
    public void serviceFreeAndResetPlayer() {
        LogUtil.debug(TAG, "serviceFreeAndResetPlayer~~~~");
        if (playerThread != null) {
            playerThread.resetAndPreparePlayer();
        }
        msgHandler.removeCallbacks(showEncryptMsg);
        hideSmallTip();
    }

    /**
     * DVB播放消息回调：释放无需复位player
     */
    public void serviceFreeWithoutResetPlayer() {
        LogUtil.debug(TAG, "serviceFreeWithoutResetPlayer~~~~");
        fullBack.setVisibility(View.GONE);
        msgHandler.removeCallbacks(showEncryptMsg);
        hideSmallTip();
    }

    /**
     * DVB播放消息回调：加密节目
     */
    public void serviceScrambled() {
        LogUtil.debug(TAG, "serviceScrambled~~~~");
        msgHandler.removeCallbacks(showEncryptMsg);
        msgHandler.postDelayed(showEncryptMsg, 2000);
    }

    /**
     * DVB播放消息回调：准备player
     */
    public void serviceTsPlayerPrepared() {
        LogUtil.debug(TAG, "serviceTsPlayerPrepared~~~~");
    }

    /**
     * DVB播放消息回调：信号差
     */
    public void serviceSignalBad() {
        LogUtil.debug(TAG, "serviceSignalBad~~~~");
        showSmallTip(R.string.tips_no_signal_msg);
        if (playerThread != null) {
            playerThread.resetPlayer();
        }
    }

    /**
     * DVB播放消息回调：信号好
     */
    public void serviceSignalGood() {
        LogUtil.debug(TAG, "serviceSignalGood~~~~");
        hideSmallTip();
    }

    /**
     * DVB播放消息回调：停止播放
     */
    public void serviceStop() {
        LogUtil.debug(TAG, "serviceStop~~~~");
        hideSmallTip();
        if (playerThread != null) {
            playerThread.stopPlayer();
        }
    }

    @Override
    void onNetworkOk() {
        LogUtil.debug(TAG, "onNetworkOk ~~~");
    }

    @Override
    void onNetworkFail() {
        LogUtil.debug(TAG, "onNetworkFail ~~~");
    }

    /**
     * 退出应用
     * @param background 是否退到后台，true表示退到后台，false表示不退到后台
     */
    public void exitApk(boolean background) {
        LogUtil.debug(TAG, "exitApk is in");
        exitLiveApp(background);
    }

    @Override
    public void handleServiceCallbackMsg(int i, Object o) {
        LogUtil.debug(TAG, "handleServiceCallbackMsg:" + i + " o:" + o);
        Message handlerMsg = msgHandler.obtainMessage(i, o);
        handlerMsg.sendToTarget();
    }
}
